package rpc

import (
	"common/config"
	"common/discovery"
	"common/logs"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/resolver"
	"reflect"
	"user/pb"
)

var (
	UserClient pb.UserServiceClient
)

func Init() {
	// etcd 解析器
	resolver.Register(discovery.NewResolver(config.Conf.Etcd))
	domain := config.Conf.Domain
	userDomain := domain["user"]
	initClient(userDomain.Name, userDomain.LoadBalance, &UserClient)
}

func initClient(name string, loadBalance bool, client interface{}) {
	addr := fmt.Sprintf("%s://%s", discovery.Etcd_Name, name)
	opts := []grpc.DialOption{
		grpc.WithTransportCredentials(insecure.NewCredentials())}
	// 负载均衡策略
	if loadBalance {
		opts = append(opts, grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"LoadBalancingPolicy": "%s"}`, "round_robin")))
	}
	// gRPC 客户端
	conn, err := grpc.DialContext(context.TODO(), addr, opts...)
	//conn, err := grpc.NewClient(addr, opts...)
	if err != nil {
		logs.Fatal("rpc connect etcd error:%v", err)
	}
	switch c := client.(type) {
	case *pb.UserServiceClient:
		*c = pb.NewUserServiceClient(conn)
	default:
		logs.Fatal("unsupported client type:%s", reflect.TypeOf(client))
	}
}
